<template>
  <div class="edu-page-warp">
    <div class="">
      <condition-card :searchParm="{}" @reset="reset" @search="searchList" label-width="110px" label-position="right">
        <el-row style="height: 50px;">
          <!-- :gutter="24" -->
          <el-col :span="8">
            <el-form-item :label="$t('administrationClass.grade')">
              <el-date-picker class="search-item" :clearable="false" v-model="queryForm.condition.grade" @change="handleGradeChange" value-format="yyyy" type="year" :placeholder="$t('graduationDesign.pleaseChoose')" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('administrationClass.college')">
              <el-select v-model="queryForm.condition.college" @change="collegeChange" clearable filterable style="width:100%">
                <el-option v-for="item in options.college" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('administrationClass.major')">
              <el-select v-model="queryForm.condition.major" clearable filterable style="width:100%">
                <el-option v-for="item in options.major" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="理论成绩">
              <el-col :span="11">
                <el-form-item prop="min">
                  <el-input v-model="queryForm.condition.min" type="number" min=0 placeholder="请输入" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item prop="max">
                  <el-input v-model="queryForm.condition.max" type="number" min=0 placeholder="请输入" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>
      <el-card shadow="never">
        <div class="edu-page-title">理论学习成绩管理</div>
        <div class="edu-opertion-bar">
          <div class="float-left">
            <KeywordInput v-model="queryForm.condition.studentName" @enter="searchList" placeholder="请输入学号或姓名搜索"></KeywordInput>
          </div>
          <div class="float-right">
            <!-- v-premit="add_tutor -->
            <!-- 新增 -->
            <el-button @click="handleClick('ADD')" type="primary">{{$t('common.btn.add')}}</el-button>
            <el-dropdown @command="handleCommand">
              <el-button>
                导入
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="import">{{$t('message.import')}}</el-dropdown-item>
                <el-dropdown-item command="download">{{$t('message.down')}}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-upload style="display: none;" ref="upload" accept=".xlsx,.xls" action="/api/scoremanagementservice/labourTheoryScore/import" :on-success="handlerSuccess" :on-error="handleUploadError" :auto-upload="true" :show-file-list="false">
              <span slot="trigger" ref="importBtn">{{$t('universityManagement.lead')}}</span>
            </el-upload>
            <el-button @click="onExport">{{$t('message.export')}}</el-button>
            <el-button type="danger" @click="handleClick('MDEL')">删除</el-button>
          </div>
        </div>
        <el-table :order="false" :selection="true" @selection-change="handleSelectionChange" :data="labourList">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column :label="$t('examinInquiry.studentNumber')" prop="studentId" fixed="left" min-width="80" />
          <el-table-column :label="$t('examinInquiry.fullName')" prop="studentName" min-width="80" />
          <el-table-column :label="$t('examinInquiry.grade')" prop="grade" min-width="70" />
          <el-table-column :label="$t('examinInquiry.college')" prop="collegeI18n" min-width="140" show-overflow-tooltip />
          <el-table-column :label="$t('examinInquiry.major')" prop="majorI18n" show-overflow-tooltip min-width="140" />
          <el-table-column label="理论成绩" prop="score" show-overflow-tooltip min-width="70" />
          <el-table-column :label="$t('message.operating')" fixed="right" width="160">
            <template slot-scope="scope">
              <div>
                <el-button type="text" @click.stop="handleClick('EDIT', scope.row)" size="mini">{{$t('message.edit')}}</el-button>
                <el-button type="text" @click.stop="handleClick('DEL', scope.row)" size="mini">{{$t('message.delete')}}</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="edu-pagination">
          <div class="float-right">
            <el-pagination :current-page="queryForm.pageNum_" :page-sizes="[10,20, 50, 100, 500, 1000]" :page-size="queryForm.pageSize_" :total="total_" layout="total, sizes, prev, pager, next, jumper" style="float: right;margin:10px 60px 0 0;" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </div>
      </el-card>
      <!-- 弹框 -->
      <edu-dialog :title="dialogTitle" width="600px" ref="updateDialog" :auto-height="true" @close="resetAddForm">
        <el-form :model="createForm" ref="createForm" label-width="100px" label-suffix=":">
          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('examinInquiry.studentNumber')" prop="studentId" :rules="[
                  { required: true, message: $t('请输入数字'), trigger: 'blur', }
                ]">
                <!-- maxlength="16" -->
                <el-input v-model="createForm.studentId" type="number" min=0 placeholder="请输入" @keyup.enter.native="blurFun" @blur="blurFun" @keyup.native="keyupFun" onkeyup.native="value=value.replace(/[^\d.]/g,'')"></el-input>
              </el-form-item>
            </el-col>
            <!-- onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" -->
            <el-col :span="12">
              <el-form-item label="姓名" prop="studentName" :rules="[
                  { required: true, message: $t('message.inputRequired'), trigger: 'blur,change' }
                ]">
                <el-input v-model="createForm.studentName" placeholder="" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年级" prop="grade" :rules="[
                  { required: true, message: $t('message.inputRequired'), trigger: 'blur,change' }
                ]">
                <el-input v-model="createForm.grade" placeholder="" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学院" prop="collegeI18n" :rules="[
                  { required: true, message: $t('message.inputRequired'), trigger: 'blur,change' }
                ]">
                <el-input v-model="createForm.collegeI18n" placeholder="" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('label.major')" prop="majorI18n" :rules="[
                  { required: true, message: $t('message.inputRequired'), trigger: 'blur' }
                ]">
                <el-input v-model="createForm.majorI18n" placeholder="" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="理论成绩" prop="score" :rules="[
                  { required: true, message: $t('请输入数字'), trigger: 'blur,change' }
                ]">
                <el-input v-model="createForm.score" placeholder="" type="number" min=0 onkeyup.native="value=value.replace(/[^\d.]/g,'')"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="buttons">
          <el-button @click="close(createForm)">{{$t('message.cancel')}}</el-button>
          <el-button @click="submitForm" type="primary" :disabled="btnTip">{{$t('message.submit')}}</el-button>
        </span>
      </edu-dialog>
    </div>
  </div>

</template>
<script>
import api from 'common/src/api/score/bachelor/labourCourse';
import tools from 'common/src/views/underGraduationDesign/tools.js';
import examinationStudentsApi from 'common/src/api/welcomeService/examinationStudents'
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import dayjs from 'dayjs'
// import { message } from 'common/src/utils/resetMessage';
const defaultCreateForm = {
  studentId: null,
  studentName: null,
  professionI18n: null,
  grade: '',
  score: '',
  collegeI18n: '',
  majorI18n: ''
};
// export function studentNumberReg(rule, value, callback){
//   const reg = /[^\d.]/g;
//   if(reg.test(value)){
//     return callback()
//   }else{
//     return callback(new Error('只能为数字'))
//   }

// }

// 院聘导师库
export default {
  name: "",
  components: {

  },
  computed: {
  },
  mounted() {
    this.Scorelist();
    this.getOptions()
  },
  watch: {
    'createForm.studentId'(newValue, oldValue) {
      if (newValue && newValue.length > 16) {
        this.createForm.studentId = newValue.substring(0, 16);
      }
    },
    'createForm.score'(newValue, oldValue) {
      let reg=/^\d+\.\d+$/;//是否是小数
      let reg2=/^\d{1,3}(\.\d{1,2})?$/;//是否是整数3位和小数2位
      if(!reg.test(newValue)&&newValue){//不是小数
        if(newValue.length>3){
          this.createForm.score = newValue.substring(0, 3);
        }
      }else{
        if(newValue&&newValue.split('.')[1]&&newValue.split('.')[1].length>2){
          this.createForm.score = parseFloat(this.createForm.score).toFixed(2);
        }
      }
    },
  },
  data() {
    return {
      dialogTitle: '',
      multipleSelection: [],
      labourList: [],
      mode: '',
      btnTip: false,
      btnTip2: false,
      rows: null,
      total_:null,
      queryForm: {
        pageNum_: 1,
        pageSize_: 10,
        condition: {
          grade: String(new Date().getFullYear()), // 年级
          college: '', // 学院
          major: '', // 专业
          min: null,
          max: null,
          page: true,
          studentName: ''
        }
      },
      options: {
        college: [],
        major: []
      },
      queryParams: {

      },
      message: '',
      createForm: UTILS.clone(defaultCreateForm)
    };
  },
  methods: {
    searchList() {
      if (parseFloat(this.queryForm.condition.min) > parseFloat(this.queryForm.condition.max)) {
        this.$message('理论成绩最小数不可大于最大数');
        return
      }
      this.Scorelist();
    },
    // 筛选条件字典查询
    Scorelist() {
      api.labourTheoryScorelist(this.queryForm).then(res => {
        if (res.code === 200) {
          this.labourList = res.data.list;
          this.total_ = res.data.total_;
        }
      });
    },
    // 重置筛选框
    reset() {
      this.queryForm = {
        pageNum_: 1,
        pageSize_: 10,
        condition: {
          grade: String(new Date().getFullYear()), // 年级
          college: '', // 学院
          major: '', // 专业
          min: null,
          max: null,
          page: true,
          studentName: ''
        }
      }
      this.searchList()
      //清空专业
      this.options.major=[]
      this.queryForm.condition.major=null
    },
    keyupFun(val) {
      this.btnTip = true;
    },
    //新增 输入学号带入学生信息 focusFun
    blurFun(val) {
      setTimeout(() => {
        if (this.createForm.studentId && !this.btnTip2) {
          api.selectStudentInfoByStuId(this.createForm.studentId).then(res => {
            if (res.code === 200) {
              if (res.data) {
                this.btnTip = false;
                //this.createForm = res.data;
                if (res.data.studentName) {
                  this.createForm.studentName = res.data.studentName;//姓名
                }
                if (res.data.grade) {
                  this.createForm.grade = res.data.grade;//年级
                }
                if (res.data.collegeI18n) {
                  this.createForm.collegeI18n = res.data.collegeI18n;//学院
                }
                if (res.data.majorI18n) {
                  this.createForm.majorI18n = res.data.majorI18n;//专业
                }
              } else {
                if (this.createForm.studentId) {
                  //this.$refs.updateDialog.open();
                  this.btnTip = true;
                  this.createForm.studentName = '';
                  this.createForm.grade = '';
                  this.createForm.collegeI18n = '';
                  this.createForm.majorI18n = '';
                  this.$message({
                    type: 'warning',
                    message: '此学号不存在'
                  });
                  return
                }
              }
            }
          }).catch(e => {
            // reject(e);
          })
        }
      }, 300)
    },
    //新增 编辑 删除
    handleClick(mode, row) {
      this.btnTip = false;
      this.btnTip2 = false;
      this.mode = mode;
      let copy = Object.assign({}, row)
      this.rows = copy;
      switch (mode) {
        case 'ADD':
          this.dialogTitle = this.$t("message.add");
          this.createForm = UTILS.clone(defaultCreateForm);
          this.$refs.updateDialog.open();
          break
        case 'MDEL':
          if (this.multipleSelection.length === 0) {
            this.$message({
              type: 'warning',
              message: '请先勾选需要删除的列表记录'
            })
            return
          }
          this.$confirm('确认删除选中, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              api.labourTheoryScoreDel(this.multipleSelection.map(item => item.id)).then(res => {
                if (res.code == 200) {
                  this.$message({
                    type: 'success',
                    message: '删除成功!'
                  })
                  this.$refs.updateDialog.close();
                  this.searchList()
                }
              })
            })
            .catch(() => {
            })
          break
        case 'DEL':
          this.$confirm('确认删除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let ids = [];
            ids.push(row.id);
            api.labourTheoryScoreDel(ids).then(res => {
              if (res.code == 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.$refs.updateDialog.close();
                this.searchList()
              }
            })
          })
          break
        case 'EDIT':
          this.dialogTitle = this.$t("message.edit");
          this.$refs.updateDialog.open();
          this.TheoryDetails(row.id);
          break
      }
    },
    //详情
    TheoryDetails(id) {
      api.labourTheoryDetails(id).then(res => {
        if (res.code === 200) {
          this.createForm = res.data;
        }
      });
    },
    //添加保存
    submitForm() {
      this.$refs.createForm.validate(valid => {
        if (valid) {
          if (this.createForm.score < 0) {
            this.$message('理论成绩不能是负数');
            return
          }
          let reg2=/^\d{1,3}(\.\d{1,2})?$/;//是否是整数3位和小数2位
          if(!reg2.test(parseFloat(this.createForm.score))){
            this.$message('理论成绩不可大于三位数');
            return
          }
          if (this.mode == 'ADD') {
            let data = {
              studentId: this.createForm.studentId,
              score: this.createForm.score
            }
            api.labourTheoryScoreAdd(data).then(res => {
              if (res.code === 200) {
                this.$refs.updateDialog.close();
                this.searchList()
              }
            });
          } else if (this.mode == 'EDIT') {
            let data = {
              id: this.rows.id,
              studentId: this.createForm.studentId,
              score: this.createForm.score
            }
            api.labourTheoryScoreedit(data).then(res => {
              if (res.code === 200) {
                this.$refs.updateDialog.close();
                this.searchList()
              }
            });
          }

        }
      });
    },
    handleGradeChange() {
      this.options.major=[];
      this.queryForm.condition.major=null;
      if(this.queryForm.condition.college){
        this.collegeChange(this.queryForm.condition.college);
      }
    },
    // 筛选条件字典查询
    getOptions() {
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ['X_YX']
      };
      queryDic(data).then(res => {
        UTILS.fillSelect(
          {            
            college: "X_YX" // 学院
          },
          res.data,
          this.options
        );
      });
    },
    // 修改学院
    collegeChange(val) {
      this.options.major = []
      this.queryForm.condition.major = ''
      let data = {
        lang: this.$store.getters.language || 'cn',
        type: 'allChild',
        keys: ['G_ZY'],
        filter: {
          grade: this.queryForm.condition.grade,
          prefix: [val],
          specilaCode: 'XY2ZY',
          facultys: [val]
        }
      }
      queryDic(data).then(res => {
        UTILS.fillSelect(
          {
            major: 'G_ZY' // 专业
          },
          res.data,
          this.options
        )
      })
    },
    close(data) {
      this.btnTip = false;
      this.btnTip2 = true;
      if (data.id) {//编辑
        this.closeDialog();
      } else {
        this.$refs.createForm.clearValidate();
        this.$refs.updateDialog.close();
      }
    },
    closeDialog() {
      this.$refs.createForm.clearValidate();
      this.$refs.updateDialog.close();
    },
    resetAddForm() {
      this.$refs.createForm.clearValidate();
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 分页
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val
      this.searchList(this.queryForm)
    },
    // 分页
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val
      this.queryForm.pageNum_ = 1
      this.searchList(this.queryForm)
    },
    // 处理导入
    handleCommand(command) {
      if (command && command === "import") {
        // 模板导入
        this.$refs.importBtn.click();
      } else if (command && command === "download") {
        // 模板下载
        this.downloadTemplate();
      }
    },
    // 模板下载
    downloadTemplate() {
      window.location.href =
        "/api/scoremanagementservice/labourTheoryScore/template";
    },
    //导入文件成功后
    handlerSuccess(res) {
      if (res.code == 200) {
        let loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, .48)'
        })
        this.delayImportRequest(res.data.key, loading)
      }
    },
    async delayImportRequest(key, loading) {
      await new Promise(resolve => setTimeout(resolve, 3000))
      api.getImportStatus(key)
        .then(res => {
          if (res.code == 200 && res.data.status) {
            loading.close()
            if (res.data.success) {
              this.$message({
                type: 'success',
                message: '导入成功'
              })
              // this.$refs.importDialog.close()
              this.searchList()
            } else {
              this.$refs.upload.clearFiles()
              let msg = res.data.msg || '导入失败'
              this.$message({
                type: 'error',
                message: msg + ',请重新导入'
              })
            }
          }
          // else if(res.code == 400){
          //   this.$refs.upload.clearFiles()
          //     let msg = res.message || '导入失败'
          //     this.$message({
          //       type: 'error',
          //       message: msg.message
          //     })
          // }
          else {
            this.delayImportRequest(key)
          }
        })
        .catch(ex => {
          this.delayImportRequest(key)
        })
    },

    handleUploadError(err) {
      let myError=err.toString();//转字符串
      myError=myError.replace("Error: ","") // 去掉前面的" Error: "
      myError=JSON.parse(myError);//转对象
      this.$message({
        type: 'error',
        message: myError.message
      })
    },
    // 导出
    onExport() {
      let data = _.cloneDeep(this.queryForm.condition);
      data.studentIds = this.multipleSelection.map(item=>item.studentId);
      api.exportData(data).then(res => {
        if (res.code == 200) {
          tools.downloadFile(res.data.key, "理论环节成绩管理.xls", null, this);
        }
      })
    }
  }
};
</script>
<style lang="scss" scoped>
.edu-page-title {
    margin-bottom: 30px;
}
.line {
    text-align: center;
}
</style>
